package com.lt.flashcard.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Path;
import org.zkoss.zk.ui.event.CheckEvent;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.Flashcard;
import com.lt.flashcard.model.entity.FlashcardSet;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.FlashcardService;
import com.lt.flashcard.model.service.FlashcardSetService;
import com.lt.flashcard.model.service.Repository;

public class V_flashcard_list_detail {
    private FlashcardSet flashcardSet = null;
    private Flashcard flashcard;

    private User user;

    @Wire(".chkAll")
    Checkbox chkAll;
    @Wire("#region_list_f")
    Div region_list_f;
    @Wire
    Textbox name_set;
    @Wire
    Textbox description_set;
    @Wire
    Textbox tags_set;
    @Wire
    Listbox list_set;

    @Init
    public void flashcardListDetail() {
        try {
            Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
            FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");
            flashcardSet = ctrl.getFlashcardSet();
            getFlashcardsets();
        } catch (Exception e) {
            // TODO: handle exception
        }

        user = Utility.getUser();
    }

    @AfterCompose
    public void afterCompose(@ContextParam(ContextType.VIEW) Component view) {
        Selectors.wireComponents(view, this, false);
    }

    public ListModelList<FlashcardSet> getFlashcardsets() {
        FlashcardSetService srv = Repository.getInstance().getFlashcardSetService();
        List<FlashcardSet> flashcardsets = srv.getFlashcardsetsOfCurrUser(user, true);
        return new ListModelList<FlashcardSet>(flashcardsets);
    }

    // ----------------setter and getter-------

    public void setFlashcardSet(FlashcardSet flashcardSet) {
        this.flashcardSet = flashcardSet;
    }

    public FlashcardSet getFlashcardSet() {
        if (flashcardSet == null) {
            flashcardSet = new FlashcardSet();
        }
        Clients.evalJavaScript("$.calculateTerm()");
        return flashcardSet;
    }

    public Flashcard getFlashcard() {
        return flashcard;
    }

    public void setFlashcard(Flashcard flashcard) {
        this.flashcard = flashcard;
    }

    // ---------------end setter and getter--------------

    @Command
    @NotifyChange("flashcardSet")
    public void editFlashcardExistSelected(@BindingParam("flashcard") Flashcard eFlashcard) throws IOException {
        Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
        FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");

        Flashcard cfc = ctrl.getFlashcard();

        if ((cfc != null && eFlashcard.getId().equals(cfc.getId())) || ctrl.getFcIds().contains(eFlashcard.getId())) {
            Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
            return;
        }

        if (cfc != null
                && (!Utility.isEmptyString(cfc.getTerm()) || !Utility.isEmptyString(cfc.getDefinition()) || !Utility.isEmptyString(cfc.getImage()))) {// add to
                                                                                                                                                      // queue
            ctrl.getFcIds().add(eFlashcard.getId());
            ctrl.renderNotifyEdit();
            Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
        } else {
            ctrl.setFlashcard(eFlashcard);
            ctrl.updateFlashcardValue();
            Clients.evalJavaScript("$('html, body').animate({scrollTop: $('#editflashcard').offset().top }, 600);");
            Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
        }
    }

    @Command
    @NotifyChange("flashcardSet")
    public void deleteFlashcardExistSelected(@BindingParam("flashcard") Flashcard eFlashcard) {

        try {
            flashcardSet.getFlashcards().remove(eFlashcard);
            FlashcardService fSrv = Repository.getInstance().getFlashcardService();
            // TODO update to use method of flashcardset
            fSrv.delete(eFlashcard);
            FlashcardSetService fsSrv = Repository.getInstance().getFlashcardSetService();
            fsSrv.updateTotalFlashcards(flashcardSet);
            fsSrv.save(flashcardSet);
            Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
        } catch (Exception e) {
            Messagebox.show(e.getMessage());
        }

    }

    @GlobalCommand
    @NotifyChange("flashcardSet")
    public void updateFlashcardList(@BindingParam("flashcardSet") FlashcardSet flashcardSet) {
        // update FlashcardSet
        this.flashcardSet = flashcardSet;
        Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
    }

    @Command
    @NotifyChange("selected")
    public void selectAll(CheckEvent event) {
        Iterable<Component> child = region_list_f.queryAll("checkbox.select_small");

        if (child != null) {
            for (Component com : child) {
                Checkbox checkbox = (Checkbox) com;
                checkbox.setChecked(chkAll.isChecked());
            }
        }

        Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
        Clients.evalJavaScript("$.countChecked();");
    }

    @Command
    @NotifyChange("flashcardSet")
    public void deleteSelected() {
        FlashcardService fSrv = Repository.getInstance().getFlashcardService();
        FlashcardSetService fsSrv = Repository.getInstance().getFlashcardSetService();
        Iterable<Component> child = region_list_f.queryAll("checkbox.select_small");
        int count = 0;
        if (child != null) {
            try {
                for (Component com : child) {
                    Checkbox checkbox = (Checkbox) com;
                    if (checkbox.isChecked()) {
                        Flashcard eFlashcard = checkbox.getValue();
                        flashcardSet.getFlashcards().remove(eFlashcard);
                        fSrv.delete(eFlashcard);
                        count++;
                    }
                }
                if (count > 0) {
                    if (flashcardSet.getId() != null) {
                        Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
                        FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");
                        ctrl.setFlashcardSet(flashcardSet);
                        fsSrv.updateTotalFlashcards(ctrl.getFlashcardSet());
                        fsSrv.save(ctrl.getFlashcardSet());
                    }
                    Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
                } else {
                    Clients.evalJavaScript("showNotice('','please select a flashcard');");
                }
            } catch (Exception e) {
                Messagebox.show(e.getMessage());
            }
        } else {
            Clients.evalJavaScript("showNotice('','No have flashcard');");
        }
    }

    @Command
    public void addIntoSet(@BindingParam("flashcard") Flashcard flashcard) {
        if (flashcard != null) {
            this.flashcard = flashcard;
        } else {
        }

    }

    /**
     * choose flashcard set and save flashcards are selected into flashcard set choosed
     */
    @Command
    public void saveIntoFlashcardSet() {
        FlashcardSetService fsSrv = Repository.getInstance().getFlashcardSetService();
        if (flashcard != null) {
            if (list_set.getSelectedItem() == null) {
                Clients.evalJavaScript("showNotice('','Vui lòng chọn một flashcard set!')");
                return;
            }
            FlashcardSet setSelected = list_set.getSelectedItem().getValue();

            Flashcard insertFlashcard = new Flashcard(flashcard);
            insertFlashcard.setOriflashcardset(flashcardSet);
            if (setSelected != null) {
                setSelected.getFlashcards().add(insertFlashcard);
                fsSrv.updateTotalFlashcards(setSelected);
                fsSrv.save(setSelected);
                String notify = "Đã thêm flashcard: " + flashcard.getTerm() + " vào bộ flashcard set: " + setSelected.getName();
                Clients.evalJavaScript("showNotice('','" + notify + "');");
                flashcard = null;
            } else {
                Clients.evalJavaScript("showNotice('','Vui lòng chọn một flashcard set!')");
                return;
            }
        } else {
            if (list_set.getSelectedItem() == null) {
                Clients.evalJavaScript("showNotice('', 'Vui lòng chọn một bộ từ')");
            } else {
                FlashcardSet setSelected = list_set.getSelectedItem().getValue();
                Iterable<Component> child = region_list_f.queryAll("checkbox.select_small");
                Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
                FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");
                List<Checkbox> chkFlashcards = new ArrayList<Checkbox>();
                for (Component comp : child) {
                    Checkbox chk = (Checkbox) comp;
                    chkFlashcards.add(chk);
                }

                fsSrv.saveFlashcardsIntoSet(chkFlashcards, ctrl.getFlashcardSet(), setSelected);
            }
        }
    }

    /**
     * create new flashcard set with name typed and save flashcards are seleted into new flashcard set
     */
    @Command
    public void createAndSaveFlashcardSet() {
        FlashcardSetService fsSrv = Repository.getInstance().getFlashcardSetService();
        if (flashcard != null) {
            if (name_set.getValue().length() > 0) {
                FlashcardSet newSet = new FlashcardSet();
                newSet.setName(name_set.getValue());
                newSet.setAuthor(Utility.getUser());

                Flashcard insertFlashcard = new Flashcard(flashcard);
                insertFlashcard.setOriflashcardset(flashcardSet);
                newSet.getFlashcards().add(insertFlashcard);
                fsSrv.updateTotalFlashcards(newSet);

                fsSrv.save(newSet);
                flashcard = null;
                Executions.getCurrent().sendRedirect("/flashcard.zul?task=edit&id=" + newSet.getId().toString(), "_blank");

            } else {
                Clients.evalJavaScript("showNotice('','Vui lòng nhập tên flashcard set');");
            }
        } else {
            Iterable<Component> child = region_list_f.queryAll("checkbox.select_small");
            Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
            FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");
            List<Checkbox> chkFlashcards = new ArrayList<Checkbox>();
            for (Component comp : child) {
                Checkbox chk = (Checkbox) comp;
                chkFlashcards.add(chk);
            }

            fsSrv.createSetAndAddFlashcardsIntoSet(chkFlashcards, ctrl.getFlashcardSet(), name_set.getValue());
        }
    }

    /**
     * edit flashcards selected
     */
    @Command
    public void editSelected() {
        FlashcardService fSrv = Repository.getInstance().getFlashcardService();
        Iterable<Component> child = region_list_f.queryAll("checkbox.select_small");
        int count = 0;
        if (child != null) {
            try {
                Component com = Path.getComponent("//page_flashcardlist/flashcardlist_parent");
                FlashcardCtrl ctrl = (FlashcardCtrl) com.getAttribute("$composer");
                Flashcard cfc = ctrl.getFlashcard();
                List<Long> ids = ctrl.getFcIds();

                for (Component comc : child) {
                    Checkbox checkbox = (Checkbox) comc;
                    if (checkbox.isChecked()) {
                        Flashcard eFlashcard = checkbox.getValue();

                        if ((cfc != null && eFlashcard.getId().equals(cfc.getId())) || ids.contains(eFlashcard.getId())) {
                            continue;
                        }

                        ids.add(eFlashcard.getId());
                        count++;
                    }
                }
                if (count > 0) {
                    if (cfc != null
                            && (!Utility.isEmptyString(cfc.getTerm()) || !Utility.isEmptyString(cfc.getDefinition()) || !Utility.isEmptyString(cfc
                                    .getImage()))) {// add to queue
                    } else {
                        FlashcardSet fc = ctrl.getFlashcardSet();
                        ctrl.setFlashcard(fc.getFlashcardById(ids.get(0)));
                        ids.remove(0);
                        ctrl.updateFlashcardValue();
                    }
                    ctrl.renderNotifyEdit();
                    Clients.evalJavaScript("$('.update_check :checkbox').uniform();");
                } else {
                    Clients.evalJavaScript("showNotice('','Bạn chưa chọn flashcard để edit');");
                }
            } catch (Exception e) {
            }
        } else {
            Clients.evalJavaScript("showNotice('','Bạn chưa chọn flashcard để edit');");
        }
    }
}
